package com.u17;


import java.util.*;

/**
 * @author u17
 * https://leetcode-cn.com/problems/valid-parentheses/
 */
public class Solution {

    public boolean isValid(String s) {

        if (s.length() % 2 == 1) {
           return false;
        }

        HashMap<Character, Character> hashMap = new HashMap<>();
        hashMap.put(')', '(');
        hashMap.put('}', '{');
        hashMap.put(']', '[');

        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (hashMap.containsKey(ch)) {
                if (stack.isEmpty() || !stack.peek().equals(hashMap.get(ch))) {
                    return false;
                } else {
                    stack.pop();
                }
            } else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }

    /**
     * 改进
     * @param s
     * @return
     */
    public boolean isValid2(String s) {

        if (s.length() < 1) {
            return false;
        }

        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push(')');
            } else if (s.charAt(i) == '{') {
                stack.push('}');
            } else if (s.charAt(i) == '[') {
                stack.push(']');
            } else if (stack.isEmpty() || stack.pop() != s.charAt(i)) {
                return false;
            }
        }
        return stack.isEmpty();
    }




    public static void main(String[] args) {
        Solution solution = new Solution();
        String s = "[";
        boolean valid = solution.isValid2(s);
        System.out.println(valid);
    }
}
